package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//filterName拦截器名,urlPatterns拦截的资源,这里是拦截所有资源
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;

        //获取uri路径
        String uri = req.getRequestURI();

        //定义需要放行的资源
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",
                "/user/sendMsg"
        };


        boolean check = check(urls, uri);
        //判断是否放行
        if (check){
            //放行
            filterChain.doFilter(request,response);
            return;
        }

        //判断是否登录过
        if (req.getSession().getAttribute("employee")!=null){
            //用户已登录过,直接放行
            //获取session域中的id
          Long id  = (Long) req.getSession().getAttribute("employee");
            //将id存入TreadLocal中
            BaseContext.setThreadLocal(id);
            filterChain.doFilter(request,response);
            return;
        }

        //4-2、判断登录状态，如果已登录，则直接放行
       if (req.getSession().getAttribute("user") !=null){
           log.info("用户已登录，用户id为：{}",req.getSession().getAttribute("user"));

       Long userId = (Long)req.getSession().getAttribute("user");
       BaseContext.setThreadLocal(userId);
       filterChain.doFilter(request,response);
       //防止内存泄漏
           System.out.println(" BaseContext.remove();执行了");
           BaseContext.remove();
           return;
       }
        //没有登录,则返回未登录结果,通过输出流的方式响应给浏览器
        res.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param uri
     * @return
     */
    public boolean check(String[] urls,String uri){

        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, uri);
            if (match){
                return true;
            }
        }
        return false;
    }
}
/*
* ？匹配一个字符(matches one character)。
*  匹配0个或者多个字符 ( matches zero or more characters)。
** 匹配url中的0个或多个子目录 (matches zero or more directories in a path)
{spring:[a-z]+} 匹配满足正则表达式[a-z]+的路径，这些路径赋值给变量"spring" (matches the regexp [a-z]+ as a path variable named "spring"）
————————————————
* */